<?php
require('../../config/session.php');
$page_title = 'Add Books';
include('includes/header.html');

function check_set($val,$nam) {
    if (empty($val)) {
        echo "<p class=\"error\">Error: " . $nam . " missing</p>\n";
        return true;
    } else {
        return false;
    }
}

$failure_happened = false;
if (count($_POST) > 0) {
    $failure_happened = check_set($_POST['book_title'],"Book Title");
    $failure_happened = check_set($_POST['book_author'],"Book Author") or $failure_happened;
    $failure_happened = check_set($_POST['book_year'],"Book Year") or $failure_happened;
    $failure_happened = check_set($_POST['book_isbn'],"Book ISBN") or $failure_happened;

    if (!$failure_happened) {
        // check if the isbn is valid
        $isbn_valid = '/^[0-9][0-9-]*[0-9]$/';
        if (!preg_match($isbn_valid, $_POST['book_isbn'])) {
            $failure_happened = true;
            echo "<p class=\"error\">Error: ISBN does not follow valid format</p>\n";
        }
        
        $year_valid = '/^[0-9]{4}$/';
        if (!preg_match($year_valid, $_POST['book_year'])) {
            $failure_happened = true;
            echo "<p class=\"error\">Error: Year must be four digits</p>\n";
        }
    }
}
?>

<h1>Add a Title</h1>

<p>
In order to add a book title, insert the information below and select Confirm.
</p>

<?php
require ('../../config/mysqli_connect.php'); // Connect to the db.

// have a table of input to add the book
?>
<form action="add_title.php" method="post">
    <p>Title: <input type="text" name="book_title" size="20" maxlength="60" /> </p>
    <p>Author: <input type="text" name="book_author" size="20" maxlength="60" /> </p>
    <p>Year: <input type="text" name="book_year" size="20" maxlength="60" /> </p>
    <p>ISBN: <input type="text" name="book_isbn" size="20" maxlength="60" /> </p>
    <p><input type="submit" value="Add Title" /></p>
</form>

<?php
// Attempt to add a book
if (count($_POST) > 0 and !$failure_happened) {
    $stmt = $dbc->prepare("INSERT INTO Books VALUES(NULL, ?, ?, ?, ?)"); // isbn, auth, titl, year
    $stmt->bind_param("sssd", $_POST['book_isbn'], $_POST['book_author'], $_POST['book_title'], $_POST['book_year']);
    $stmt->execute();

    echo "<b>Book successfully added.</b>";
}

mysqli_close($dbc); // Close the database connection.
?>

<?php include ('includes/footer.html'); ?>
